import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/core/utils/shared_preferences_utils.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class LifeSearchHistoryNotifier
    extends AutoDisposeAsyncNotifier<List<String>> {
  @override
  Future<List<String>> build() async {
    return await fetchData();
  }

  Future<void> insertData(String keyword) async {
    if (keyword.trim().isEmpty) return;
    
    final spUtils = await SPUtils.getInstance();
    bool ret = await spUtils.headStringList(
      CommonConfig.klifeSearchKeyWordHistory,
      [keyword],
    );
    if (ret) {
      await fetchData();
    }
    return;
  }

  Future<List<String>> fetchData() async {
    final spUtils = await SPUtils.getInstance();
    List<String> strList = spUtils.getStringList(
      CommonConfig.klifeSearchKeyWordHistory,
    );
    state = AsyncData(strList);
    return strList;
  }

  Future<void> clear() async {
    final spUtils = await SPUtils.getInstance();
    spUtils.remove(CommonConfig.klifeSearchKeyWordHistory);
    state = AsyncData([]);
    return;
  }
}

final lifeSearchHistoryProvider =
    AutoDisposeAsyncNotifierProvider<LifeSearchHistoryNotifier, List<String>>(
      LifeSearchHistoryNotifier.new,
    );
